package com.faxsun.validation;

import javax.annotation.Resource;

import org.apache.commons.validator.GenericValidator;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.core.service.CustomerService;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.faxsun.controller.account.MergeAccountForm;


public class FSMergeAccontValidator implements Validator {

	@Resource(name = "blCustomerService")
	protected CustomerService customerService;

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void validate(Object target, Errors errors) {
		MergeAccountForm form = (MergeAccountForm) target;
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailAddress",
				"emailAddress.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
				"password.required");

		if (!errors.hasErrors()) {

			// is this a valid email address?
			if (!GenericValidator.isEmail(form.getEmailAddress())) {
				errors.rejectValue("emailAddress", "emailAddress.invalid");
				return;
			}

			// check email address to see if it is already in use
			Customer customer = customerService.readCustomerByEmail(form
					.getEmailAddress());

			if (customer == null) {
				errors.rejectValue("emailAddress", "emailAddress.invalid");
			} else {
				if (!customerService.isPasswordValid(form.getPassword(),
						customer.getPassword(), customer)) {
					errors.rejectValue("password", "password.invalid");
				}
			}
		}
	}

}
